package com.uglive.cg.model;

import android.os.Looper;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.uglive.cg.bean.ApiResult;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class ApiModel {

    private final OkHttpClient mClient = new OkHttpClient();
//    private final MediaType FORM_CONTENT_TYPE
//            = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
    private final String ip = "47.98.49.11";
//    private final String ip = "192.168.2.1";
    private final String rootUrl = "http://"+ip+":10086";
    private android.os.Handler mHadler = new android.os.Handler(Looper.getMainLooper());
    /**
     * url:/mobileLogin
     * method:POST
     * params: phoneNumber
     * result : {"status":"OK",
     * "data":{"logined":"ture"/"fase"}
     * }
     *
     * @param phoneNumber
     * @param onFailure
     * @param onSuccess
     */
    public void login(String phoneNumber, OnFailure onFailure, OnSuccess onSuccess) {
        Request  request = new Request.Builder()
                .url(rootUrl+"/mobileLogin"+"?phoneNumber="+phoneNumber)
                .method("POST",new FormBody.Builder().build())
                .build();
        call(request, onFailure, onSuccess);
    }

    /**
     * 获取仓库列表
     * url:/ckListApi
     * method:GET
     * result : {
     *              "status":"OK",
     *              "data":[]
     *          }
     */
    public  void changKuList( OnFailure onFailure, OnSuccess onSuccess) {
        Request request = new Request.Builder()
                .url(rootUrl + "/ckListApi")
                .build();
        call(request, onFailure, onSuccess);
    }
    /**
     * 入库
     * url:/joinApi
     * method:POST
     * params: param,sum,ware
     * result : {"status":"OK",
     * "data":{
     * "goodsName":"货物名称",
     * "goodsSum":"货物库存总数"
     * }
     * }
     */
    public  void ruku(String num, String barCode,String place,String phoneNumber, OnFailure onFailure, OnSuccess onSuccess) {
        RequestBody formBody = new FormBody.Builder()
                .add("param", barCode)
                .add("sum", num)
                .add("warehouse",place)
                .add("phoneNumber",phoneNumber)
                .build();
        Request request = new Request.Builder()
                .url(rootUrl + "/joinApi")
                .post(formBody)
                .build();
        call(request, onFailure, onSuccess);
    }

    /**
     * 出库
     * url:/comeApi
     * method:POST
     * params: param,sum,ware
     * result : {"status":"OK",
     * "data":{
     *          "goodsName":"货物名称",
     *          "goodsSum":"货物库存总数"
     *          }
     *        }
     */
    public void chuku(String num, String barCode,String place,String phoneNumber, OnFailure onFailure, OnSuccess onSuccess) {

        RequestBody formBody = new FormBody.Builder()
                .add("param", barCode)
                .add("sum", num)
                .add("warehouse", place)
                .add("phoneNumber",phoneNumber)
                .build();
        Request request = new Request.Builder()
                .url(rootUrl + "/comeApi")
                .post(formBody)
                .build();
        call(request, onFailure, onSuccess);
    }

    private void call(Request request, OnFailure onFailure, OnSuccess onSuccess) {
        if (!checkNetwork()) {
            onFailure.onFailure();
            return;
        }
        mClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                ToastUtils.showShortSafe("连接超时，请检查网络");
                mHadler.post(()->onFailure.onFailure());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try (ResponseBody responseBody = response.body()) {
                    if (!response.isSuccessful()) {
                        mHadler.post(() -> onFailure.onFailure());
                    }
                    String result = responseBody.string();
                    try {
                        ApiResult res = JSON.parseObject(result, ApiResult.class);
                        if (res.getStatus().equals("OK")) {
                            String json = JSON.toJSONString(res.getData());
                            mHadler.post(() ->onSuccess.onSuccess(json));
                        }else {
                            mHadler.post(() ->onSuccess.onSuccess(null));
                        }
                    } catch (Exception e) {
                        ToastUtils.showShortSafe("服务器错误");
                        mHadler.post(() -> onFailure.onFailure());
                    }
                }
            }
        });
    }


    public boolean checkNetwork() {
        if (NetworkUtils.isWifiConnected()) {
            return true;
        } else {
            ToastUtils.showShortSafe("请打开网络连接");
            return false;
        }
    }

    public interface OnFailure {
        void onFailure();
    }

    public interface OnSuccess {
        void onSuccess(String result);
    }
}
